/*
    Copyright 2006 Andrew Wilkinson <andrew@indiegigs.co.uk>

    This file is part of libgp2x.

    libgp2x is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    libgp2x is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with libgp2x; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>

#define GP2x_internal
#include "gp2x_internal.h"

#ifdef printf
#undef printf
#undef fprintf
#endif

int GP2x_register_shm;
int GP2x_memory_shm;

void GP2x_shared_memory_init(char* regfile, char* memfile) {
    GP2x_register_shm = shmget(ftok(regfile, 1), 4096, 0660);
    if(GP2x_register_shm == -1) {
        fprintf(stderr, "Unable to get register file.\n");
        exit(1);
    }
    GP2x_memory_shm = shmget(ftok(memfile, 1), 32*1024*1024, 0660);
    if(GP2x_memory_shm == -1) {
        fprintf(stderr, "Unable to get memory file.\n");
        exit(1);
    }

    GP2x_registers = shmat(GP2x_register_shm, NULL, 0);
    if((unsigned long)GP2x_registers == -1) {
        fprintf(stderr, "Unable to attach register file.\n");
        exit(1);
    }
    GP2x_upper_memory = shmat(GP2x_memory_shm, NULL, 0);
    if((unsigned long)GP2x_upper_memory == -1) {
        fprintf(stderr, "Unable to attach memory file.\n");
        exit(1);
    }
    printf("Upper memory at %lx. Registers at %lx.\n", (unsigned long)GP2x_upper_memory, (unsigned long)GP2x_registers);
    GP2x_940_OFFSET = -(((unsigned long)GP2x_upper_memory) - 0x2000000);
}

void GP2x_shared_memory_finalize() {
    shmdt((void*)GP2x_registers);
    shmdt((void*)GP2x_upper_memory);
}
